#!/usr/bin/python3/bin/python3
# -*- coding: UTF-8 -*-

import requests
import time
import urllib3
import sys
import os
import signal

scriptTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

rootdir = '/usr/local/liverecord/pid'
list = os.listdir(rootdir)
for i in range(0, len(list)):
    path = os.path.join(rootdir,list[i])
    f = open(path)
    pid = str.strip(f.readline())
    roomId = list[i]
    if pid == "":
        print('%s %s 无活动进程' % (scriptTime, roomId))
        continue

    params = {'id': roomId}
    # 获取房间开播信息
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Host': 'api.live.bilibili.com',
        'Origin': 'https://live.bilibili.com',
        'Referer': 'https://live.bilibili.com/' + roomId,
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
    }

    r = requests.get('https://api.live.bilibili.com/room/v1/Room/get_info', params=params, headers=headers).json()

    if r['code'] != 0:
        #    raise Exception('接口返回错误:'+r['message'])
        print('%s %s 接口返回错误：%s\n' % (scriptTime,roomId, r['message']))

    elif r['data']['live_status'] != 1:
        #    raise Exception('主播未开播')
        print('%s  %s 主播未开播\n' % (scriptTime, roomId))
        try:
            os.kill(int(pid), signal.SIGTERM)
        except OSError as e:
            print('%s %s 无此进程：%s' % (scriptTime,roomId,pid))
    else:
        print('%s %s 主播正在直播' % (scriptTime, roomId))
